package com.xone.xapp;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public abstract class BasicActivity extends Activity {
	
	private Timer timer;
	private VerticalViewPager headerBanner;
	private Handler handler;
	private ProgressDialog progressDialog;
	protected TextView header;
	protected Button leftButton;
	protected Button rightButton;
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(getContentView());
		leftButton = (Button)findViewById(R.id.btnPrev);
		rightButton = (Button)findViewById(R.id.btnNext);
		if (null != leftButton) {
			leftButton(leftButton);
		}
		if (null != rightButton) {
			rightButton(rightButton);
		}
		header = (TextView)findViewById(R.id.header_title);
		if (null != header) {
			header.setText(getHeaderTitle());
		}
		//垂直滚动的解决方案https://github.com/LambergaR/VerticalViewPager
		headerBanner = (VerticalViewPager)findViewById(R.id.header_adbanner_switcher);
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(true);
		progressDialog.setMessage("加载中...");
		progressDialog.setProgressStyle(R.style.progress_bar_style);
		progressDialog.setProgress(0);
	}
	
	/**
	 * 头部左边按钮的处理
	 * @param leftButton
	 */
	protected void leftButton(Button leftButton) {
		leftButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getActivity().finish();
			}
		});
	}
	
	/**
	 * 头部右边按钮的处理
	 * @param rightButton
	 */
	protected void rightButton(Button rightButton) {
		rightButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startDial();
			}
		});
	}
	
	protected void showProgress() {
		progressDialog.show();
	}
	protected void hideProgress() {
		progressDialog.dismiss();
	}
	
	/**
	 * 是否需要检测登录
	 * @return
	 */
	public boolean isLoginCheck() {
		return true;
	}
	
	public boolean isRefreshButton() {
		return false;
	}
	
	protected void onResume() {
		super.onResume();
		if (isRefreshButton()) {
			if (null != leftButton) {
				leftButton(leftButton);
			}
			if (null != rightButton) {
				rightButton(rightButton);
			}
		}
		if (isLoginCheck() && !UserInfo.login) {
			startActivity(new Intent(this, LoginActivity.class));
			this.finish();
			return;
		}
		if (!isShowBanner()) {
			return;
		}
		if (null != headerBanner) {
			handler = new Handler() {
				public void handleMessage(Message msg) {// 定义一个Handler，用于处理下载线程与UI间通讯
					if (!Thread.currentThread().isInterrupted()) {
						switch (msg.what) {
						case 2:
							if (null != headerBanner && headerBanner.getChildCount() > 1) {
								int cItem = headerBanner.getCurrentItem();
								cItem ++;
								if (cItem >= headerBanner.getChildCount()) {
									cItem = 0;
								}
								headerBanner.setCurrentItem(cItem, true);
							}
							break;
						}
					}
				}
			};
			timer = new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					Message message = new Message();  
		            message.what = 2;
		            handler.sendMessage(message);
				}
			}, Constants.BANNER_INTERVAL * 1000, Constants.BANNER_INTERVAL * 1000);
		}
		new InitBannerDataTask(this).execute();
	}
	
	protected void onPause() {
		super.onPause();
		//停止触发器并释放资源
		if (null != timer) {
			timer.cancel();
			timer.purge();
		}
		timer = null;
		handler = null;
	}
	
	public void startDial() {
		Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Constants.CUSTOMER_TEL));
		startActivity(i);
	}
	
	public boolean isShowBanner() {
		return true;
	}
	
	public Context getContext() {
		return this;
	}
	
	public Activity getActivity() {
		return this;
	}
	
	public abstract String getHeaderTitle();
	
	/**
	 * 当前实例的布局编号文件
	 * @return
	 */
	public abstract int getContentView();
	
	protected class InitBannerDataTask extends AsyncTask<String, Integer, List<JSONObject>> {
		protected Context context;
		protected ImageLoader imgLoader;
		public InitBannerDataTask(Context context) {
			this.context = context;
			imgLoader = new ImageLoader(context, ContextUtils.getScreenWidth(context));
		}
		@Override
		protected List<JSONObject> doInBackground(String... params) {
			if (isCancelled()) {
				return null;
			}
			return HttpUtils.httpGet(Constants.APP_URL + "/adbanner/adbannerJson.html", null,
					new HttpUtils.onGetSuccessListener<List<JSONObject>>() {
						@Override
						public List<JSONObject> onSuccess(int status, String result) {
							if (HttpUtils.SC_OK == status) {
								return JSONUtils.getJSONListFromIdentifyString(result, "list");
							}
							return null;
						}
					});
		}
		@Override
		protected void onPostExecute(List<JSONObject> result) {
			super.onPostExecute(result);
			if (isCancelled() ||null == result || result.isEmpty()) {
				return;
			}
			BannerAdapter adapter = new BannerAdapter(context, result);
			if (adapter.init()) {
				headerBanner.setAdapter(adapter);
				if (headerBanner.getAdapter().getCount() > 0) {
					headerBanner.setVisibility(View.VISIBLE);
				}
			}
		}
	}
	
	/**
	 * 根据级别获取显示的标题 <h1><c:choose><c:when
	 * test="${clevelUser}">零售终端等级</c:when><c:when
	 * test="${blevelUser}">市场销售等级</c:when><c:when
	 * test="${alevelUser}">国际贸易等级</c
	 * :when><c:otherwise>欢迎使用</c:otherwise></c:choose></h1>
	 * 
	 * @param title
	 * @return
	 */
	protected String getTitleByLevel(String title) {
		if (UserInfo.clevelUser) {
			return "零售终端等级";
		} else if (UserInfo.blevelUser) {
			return "市场销售等级";
		} else if (UserInfo.alevelUser) {
			return "国际贸易等级";
		}
		return title;
	}
	
	/**
	 * 根据传入的值取得当前的下拉框位置
	 * @param map
	 * @param offset
	 * @return
	 */
	protected int getIndexByMapAndOffset(Map<String, String> map, String offset) {
		String [] keys = map.keySet().toArray(new String[0]);
		for (int i = 0; i < keys.length; i++) {
			if (map.get(keys[i]).equals(offset)) {
				return i;
			}
		}
		return 0;
	}

}
